/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
 * Neither the name of the Yusuke Yamamoto nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package t4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import t4j.data.Paging;
import t4j.http.AccessToken;
import t4j.http.RequestToken;
import t4j.http.Response;
import t4j.org.json.JSONException;
import t4j.util.Constant;

/**
 *
 * @author gcwang
 *
 */
public class TBlog extends TBlogSupport {

    public static final String CONSUMER_KEY = "";

    public static final String CONSUMER_SECRET = "";

    private String baseURL = Configuration.getScheme() + Constant.BASE_URL;

    private String searchBaseURL = Configuration.getScheme() + Constant.BASE_URL;

    public TBlog() {

        super();

        format.setTimeZone(TimeZone.getTimeZone("GMT"));

        http.setRequestTokenURL(Configuration.getScheme() + Constant.BASE_URL + "oauth/request_token");
        http.setAccessTokenURL(Configuration.getScheme() + Constant.BASE_URL + "oauth/access_token");
    }

    public void setToken(String token, String tokenSecret) {
        http.setToken(token, tokenSecret);
    }

    public void setBaseURL(String baseURL) {
        this.baseURL = baseURL;
    }

    public String getBaseURL() {
        return this.baseURL;
    }

    public String getSearchBaseURL() {
        return searchBaseURL;
    }

    public void setSearchBaseURL(String searchBaseURL) {
        this.searchBaseURL = searchBaseURL;
    }

    public synchronized void setOAuthConsumer(String consumerKey, String consumerSecret) {
        this.http.setOAuthConsumer(consumerKey, consumerSecret);
    }

    public RequestToken getOAuthRequestToken() throws TBlogException {
        return http.getOAuthRequestToken();
    }

    public synchronized AccessToken getOAuthAccessToken(RequestToken requestToken) throws TBlogException {
        return http.getOAuthAccessToken(requestToken);
    }

    public synchronized AccessToken getOAuthAccessToken(String token, String tokenSecret) throws TBlogException {
        AccessToken accessToken = http.getOAuthAccessToken(token, tokenSecret);
        setUserId(accessToken.getScreenName());
        return accessToken;
    }

    public AccessToken getXAuthAccessToken(String passport, String password) throws TBlogException {
        return this.http.getXAuthAccessToken(passport, password, false);
    }

    public AccessToken getXAuthAccessToken(String passport, String password, boolean isMD5) throws TBlogException {
        return this.http.getXAuthAccessToken(passport, password, isMD5);
    }

    // **************************yuedu api***************************************/

    public String coverImage() throws TBlogException, JSONException {
        Response response = get(getBaseURL() + "/cover/image.xml", true);
        return response.asString();
    }

    public String getArticleList(String sourceId) throws TBlogException {
        Response response = get(getBaseURL() + "article/list.xml?sourceid=" + sourceId, true);
        return response.asString();
    }

    public String createBatchFavorite(String articleIds) throws TBlogException {
        Response response = get(getBaseURL() + "favorite/create_batch.xml?ids=" + articleIds, true);
        return response.asString();
    }

    public String createFavorite(String articleid) throws TBlogException {
        Response response = get(getBaseURL() + "favorite/create_batch.xml?ids=" + articleid, true);
        return response.asString();
    }

    public String accountShow(long userId) throws TBlogException{
        StringBuilder sb = new StringBuilder();
        sb.append("account/show.xml?userid=fdsafds");
        if (userId != 0) {
            sb.append("?userid=").append(userId);
        }
        Response response = get(getBaseURL() + sb.toString(), true);
        return response.asString();
    }

    public String accoutUpdate(String nickname, int gender, String introduction) throws TBlogException{
        StringBuilder sb = new StringBuilder();
        sb.append("/account/update_profile.xml?");
        if (nickname != null) {
            sb.append("nickname=").append(nickname);
        }
        sb.append("&gender=").append(gender);
        if (introduction != null) {
            try {
                sb.append("&introduction=").append(URLEncoder.encode(introduction, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                return e.getMessage();
            }
        }
        Response response = get(getBaseURL() + sb.toString(), true);
        return response.asString();
    }

    public String addCompaint(String articleId, String title, String content) throws TBlogException {
        StringBuilder sb = new StringBuilder();
        sb.append("/complaint/create.xml?articleid=").append(articleId);
        if (title != null) {
            sb.append("&title=").append(title);
        }
        if (content != null) {
            sb.append("&content=").append(content);
        }
        Response response = get(getBaseURL() + sb.toString(), true);
        return response.asString();
    }

    public String getArticleContent() throws TBlogException {
        Response response = get(getBaseURL()
                + "article/query.xml?url=http%3A%2F%2Ftech.qq.com%2Fa%2F20120316%2F000354.htm", true);
        return response.asString();
    }

    /**
     * 获取应用有权限访问的源
     */
    public String getAppSources() throws TBlogException {
        Response response = get(getBaseURL() + "app/source/ids.xml?", true);
        return response.asString();
    }

    public String createSourceComment() throws TBlogException {
        Response response = get(getBaseURL() + "/comment/book/list.xml?bookid=nb_000BHPeX_4&count=5&page=1", true);
        return response.asString();
    }

    public String listFavorite() throws TBlogException {
        Response response = get(getBaseURL() + "favorite/check.xml?articleid=7d515495-1703-4166-bee5-43ff2d201c73_1",
                true);
        return response.asString();
    }

    /**
     * 订阅源
     */
    public String subScribeSources() throws TBlogException {
        Response response = get(getBaseURL() + "source/subscribe_batch.xml?ids=011a1271-1460-476c-b0ec-2295a1fbb135_1",
                true);
        return response.asString();
    }

    /**
     * 展示文章
     */
    public String showArticle() throws TBlogException {
        Response response = get(getBaseURL() + "article/show/asdasd.xml", true);
        return response.asString();
    }

    /**
     * 展示文章
     */
    public String scoreSource(String sourceUuid,int score) throws TBlogException {
        Response response = get(getBaseURL() + "score/source/create.xml?sourceid="+sourceUuid+"&star=", true);
        return response.asString();
    }

    /**
     *
     * @param articleUuid
     * @param count
     * @param sinceId
     * @param max_id
     * @return
     * @throws TBlogException
     */
    public String commentArticle(String articleUuid, int count, long sinceId, long max_id) throws TBlogException {
        StringBuilder sb= new StringBuilder();
        sb.append("comment/article/list.xml?articleid=");
        sb.append(articleUuid);
        if(count != 0){
            sb.append("&count=").append(count);
        }
        if(sinceId != 0){
            sb.append("&since_id=").append(sinceId);
        }
        if(max_id != 0){
            sb.append("&max_id=").append("fdsafdasfd");
        }
        Response response = get(getBaseURL() + sb.toString(), true);
        return response.asString();
    }

    public String commentSource() throws TBlogException {
        Response response = get(getBaseURL()
                + "comment/source/list.xml?sourceid=82f2ab51-1586-437b-9f0e-61c4333adaea_1&since_id=133160550013316074667490122489&max_id=1&count=5&page=1",
                true);
        return response.asString();
    }

    /**
     * 删除源评论
     *
     * @return
     * @throws TBlogException
     */
    public String commentSourceDelete(long id) throws TBlogException {
        Response response = get(getBaseURL() + "comment/source/delete/" + id + ".xml", true);
        return response.asString();
    }

    /**
     * 批量显示源
     *
     * @return
     * @throws TBlogException
     */
    public String showBatchSource(String ids) throws TBlogException {
        Response response = get(getBaseURL() + "source/show_batch.xml?ids=asd34234", true);
        return response.asString();
    }

    /**
     * 获取文章详情
     *
     * @return
     * @throws TBlogException
     */
    public String articleQuery(String url) throws TBlogException {
        Response response = get(getBaseURL() + "article/query.xml?url=" + url, true);
        return response.asString();
    }

    /**
     * 文章列表
     */
    public String articleList() throws TBlogException {
        Response response = get(getBaseURL()
                + "comment/article/list.xml?articleid=7bf93d5b-1d22-4035-b653-ff5a96b78e7f_1&count=aaa&page=aaa", true);
        return response.asString();
    }

    // **************************yuedu api***************************************/

    private SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH);

    private Response get(String url, boolean authenticated) throws TBlogException {
        return http.get(url, authenticated);
    }

    protected Response get(String url, Paging paging, boolean authenticate) throws TBlogException {

        String paramList = "";

        if (null != paging) {

            List<String> params = new ArrayList<String>();
            try {

                if (paging.getMaxId() != null && !"".equals(paging.getMaxId())) {
                    params.add("max_id=" + URLEncoder.encode(String.valueOf(paging.getMaxId()), "UTF-8"));
                }
                if (paging.getSinceId() != null && !"".equals(paging.getSinceId())) {
                    params.add("since_id=" + URLEncoder.encode(String.valueOf(paging.getSinceId()), "UTF-8"));
                }
                if (-1 != paging.getCount()) {
                    params.add("count=" + URLEncoder.encode(String.valueOf(paging.getCount()), "UTF-8"));
                }
            } catch (UnsupportedEncodingException ex) {
                throw new TBlogException(ex);
            }
            paramList = join(params.toArray(new String[0]), "&");
        }

        if (paramList.isEmpty()) {
            return get(url, authenticate);
        } else {
            if (url.indexOf('?') == -1) {
                return get(url + "?" + paramList, authenticate);
            } else {
                return get(url + "&" + paramList, authenticate);
            }

        }
    }

    private static String join(Object[] array, String separator) {
        if (array == null) {
            return null;
        }
        return join(array, separator, 0, array.length);
    }

    private static String join(Object[] array, String separator, int startIndex, int endIndex) {
        if (array == null) {
            return null;
        }
        if (separator == null) {
            separator = "";
        }

        // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))
        // (Assuming that all Strings are roughly equally long)
        int bufSize = (endIndex - startIndex);
        if (bufSize <= 0) {
            return "";
        }

        bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + separator.length());

        StringBuffer buf = new StringBuffer(bufSize);

        for (int i = startIndex; i < endIndex; i++) {
            if (i > startIndex) {
                buf.append(separator);
            }
            if (array[i] != null) {
                buf.append(array[i]);
            }
        }
        return buf.toString();
    }

    public enum TopRetweetsType {
        oneHour, sixHours, oneDay, oneWeek,
    }
}
